<!--
 * @Author: your name
 * @Date: 2020-04-14 14:07:25
 * @LastEditTime: 2020-07-06 22:23:19
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vue-element-admin\src\views\enterprise\troubleDetail.vue
 -->
<template>
  <div class="app-container">
    <el-form ref="postForm" :model="postForm" class="form-container" :rules="postFormRules">
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <div class="postInfo-container">
              <el-input v-model="postForm.id" type="hidden"></el-input>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label-width="115px"
                    label="所属单位"
                    class="postInfo-container-item"
                    prop="companyId"
                  >
                    <el-select v-model="postForm.companyId" placeholder="所属单位" disabled>
                      <el-option
                        v-for="item in enterpriseList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label-width="115px"
                    label="隐患级别"
                    class="postInfo-container-item"
                    prop="dangerLevel"
                  >
                    <el-select v-model="postForm.dangerLevel" placeholder="请选择隐患级别">
                      <el-option
                        v-for="item in troubleGrades"
                        :key="item.id"
                        :label="item.dictValue"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item
                    label-width="115px"
                    label="隐患部位"
                    class="postInfo-container-item"
                    prop="dangerName"
                  >
                    <el-input placeholder="请输入隐患部位" v-model="postForm.dangerName"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label-width="115px"
                    label="专家"
                    class="postInfo-container-item"
                    prop="discoverPerson"
                  >
                    <el-input placeholder="请输入专家名称" v-model="postForm.discoverPerson"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label-width="115px"
                    label="发现日期"
                    class="postInfo-container-item"
                    prop="discoverDate"
                  >
                    <el-date-picker
                      v-model="postForm.discoverDate"
                      type="date"
                      value-format="yyyy/MM/dd"
                      placeholder="请输入发现日期"
                      class="filter-item"
                      style="width:140px"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item
                    label-width="115px"
                    label="隐患描述"
                    class="postInfo-container-item"
                    prop="dangerContent"
                  >
                    <el-input
                      placeholder="请输入隐患描述"
                      v-model="postForm.dangerContent"
                      type="textarea"
                      :rows="6"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label-width="115px" label="隐患照片上传" class="postInfo-container-item">
                    <el-upload
                      ref="upload"
                      class="upload-demo"
                      action="#"
                      :before-upload="beforeAvatarUpload"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove"
                      list-type="picture"
                      :http-request="httpRequest"
                    >
                      <el-button size="small" type="primary">点击上传</el-button>
                      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                      <img width="100%" :src="dialogImageUrl" alt />
                    </el-dialog>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label-width="115px"
                    label="整改类型"
                    class="postInfo-container-item"
                    prop="dangerRecitfyType"
                  >
                    <el-select
                      v-model="postForm.dangerRecitfyType"
                      placeholder="整改类型"
                      clearable
                      class="filter-item"
                    >
                      <el-option
                        v-for="item in troubleRectifyTypes"
                        :key="item.id"
                        :label="item.dictValue"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12" v-if="postForm.dangerRecitfyType==2">
                  <el-form-item label-width="115px" label="整改期限" class="postInfo-container-item">
                    <el-date-picker
                      v-model="postForm.recitfyOverdate"
                      type="date"
                      :clearable="false"
                      value-format="yyyy/MM/dd"
                      placeholder="请输入整改期限"
                      class="filter-item"
                    ></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="postForm.dangerRecitfyType==2">
                  <el-form-item
                    label-width="115px"
                    label="启用消息提醒"
                    class="postInfo-container-item"
                    prop="messageFlag"
                  >
                    <el-radio-group v-model="postForm.messageFlag">
                      <el-radio :label="0">不启用</el-radio>
                      <el-radio :label="1">启用</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item
                    label-width="115px"
                    label="整改要求"
                    class="postInfo-container-item"
                    prop="recitfyRequirement"
                  >
                    <el-input
                      placeholder="请输入整改要求"
                      v-model="postForm.recitfyRequirement"
                      type="textarea"
                      :rows="4"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item style="text-align: center;">
                    <el-button type="success" @click="submitForm(1)">保存草稿</el-button>
                    <el-button
                      type="primary"
                      @click="submitForm(2)"
                      :loading="loadingbut"
                    >{{loadingbuttext}}</el-button>
                    <!-- <el-button type="primary" @click="resetForm">继续录入</el-button> -->
                    <el-button @click="cancelDialog">关闭</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>
<script>
// import { validURL, validUsername } from '@/utils/validate'
import { fetchEnterpriseListByUser } from '@/api/enterprise'
import { addTrouble } from '@/api/troubles'
import { getBaseDicInfo } from '@/api/baseApi'
import moment from 'moment'
export default {
  created() {
    this.getTroubleGradesList()
    this.getRectifyTypeList()
    this.getEnterpriseList()
    if (this.isEdit) {
      //如果是编辑数据
      const id = this.$route.params && this.$route.params.id
      // this.fetchUserData(id)
    }
    this.tempRoute = Object.assign({}, this.$route)
  },
  props: {
    taskId: Number,
    companyId: Number,
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  components: {},
  data() {
    return {
      loadingbut: false, //隐患登记
      loadingbuttext: '正式发布',
      postFormRules: {
        companyId: [
          { required: true, message: '所属单位不能为空', trigger: 'blur' }
        ],
        dangerLevel: [
          { required: true, message: '隐患级别不能为空', trigger: 'blur' }
        ],
        dangerName: [
          { required: true, message: '隐患名称不能为空', trigger: 'blur' }
        ],
        // discoverPerson: [
        //   { required: true, message: '发现人不能为空', trigger: 'blur' }
        // ],
        discoverDate: [
          { required: true, message: '发现日期不能为空', trigger: 'blur' }
        ],
        dangerContent: [
          { required: true, message: '隐患描述不能为空', trigger: 'blur' }
        ],
        dangerRecitfyType: [
          { required: true, message: '整改类型不能为空', trigger: 'blur' }
        ],
        recitfyRequirement: [
          { required: true, message: '整改要求不能为空', trigger: 'blur' }
        ]
      },
      // imgfileList: [],
      troubleGrades: [], //隐患级别
      troubleRectifyTypes: [], //整改类型
      enterpriseList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      loading: false,
      postForm: {
        id: '',
        companyId: this.companyId,
        dangerLevel: '',
        dangerName: '',
        discoverDate: moment().format('YYYY/MM/DD'),
        discoverPerson: '',
        dangerContent: '',
        dangerState: '', //草稿1，正式2
        dangerRecitfyType: '', //整改类型
        recitfyOverdate: moment().format('YYYY/MM/DD'), //隐患整改期限
        recitfyRequirement: '',
        fileList: [],
        messageFlag: 0 //0不启用，1启用
      }
    }
  },
  methods: {
    cancelDialog() {
      this.$emit('closeDialog')
    },
    resetForm(companyId, dangerLevel, discoverPerson, discoverDate) {
      this.postForm = {
        id: '',
        companyId: companyId,
        dangerLevel: dangerLevel,
        dangerName: '',
        discoverDate: discoverDate,
        discoverPerson: discoverPerson,
        dangerContent: '',
        dangerState: '', //草稿1，正式2
        dangerRecitfyType: '',
        recitfyOverdate: '',
        recitfyRequirement: '',
        fileList: [],
        messageFlag: 0 //0不启用，1启用
      }
      this.$refs.upload.clearFiles()
    },
    submitForm(dangerState) {
      // console.log('this.postForm.discoverDate', this.postForm.discoverDate)
      if (dangerState == 2) {
        this.loadingbut = true
        this.loadingbuttext = '正在发布中...'
      }
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          const formData = new FormData()
          formData.append('taskId', this.taskId)
          formData.append('companyId', this.postForm.companyId)
          formData.append('dangerLevel', this.postForm.dangerLevel)
          formData.append('dangerName', this.postForm.dangerName)
          formData.append('discoverPerson', this.postForm.discoverPerson)
          formData.append('discoverDate', this.postForm.discoverDate)
          formData.append('dangerContent', this.postForm.dangerContent)
          formData.append('dangerRecitfyType', this.postForm.dangerRecitfyType)
          if (this.postForm.dangerRecitfyType == 2) {
            //限期整改
            formData.append('recitfyOverdate', this.postForm.recitfyOverdate)
            formData.append('messageFlag', this.postForm.messageFlag)
          } else {
            //非限期整改
            formData.append('recitfyOverdate', moment().format('YYYY/MM/DD'))
          }
          formData.append(
            'recitfyRequirement',
            this.postForm.recitfyRequirement
          )
          formData.append('dangerState', dangerState)
          this.postForm.fileList.forEach((file) => {
            formData.append('files', file, file.name)
          })
          // formData.append('file', this.postForm.file)
          this.$confirm('此操作将保存隐患, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              addTrouble({ formData }).then((res) => {
                if (res.code == 20000) {
                  this.$notify({
                    title: '成功',
                    message: '新增隐患成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.resetForm(
                    this.postForm.companyId,
                    this.postForm.dangerLevel,
                    this.postForm.discoverPerson,
                    this.postForm.discoverDate
                  )
                  if (dangerState == 2) {
                    this.loadingbut = false
                    this.loadingbuttext = '正式发布'
                  }
                } else {
                  this.$notify({
                    title: '失败',
                    message: '新增隐患失败',
                    type: 'error',
                    duration: 2000
                  })
                  if (dangerState == 2) {
                    this.loadingbut = false
                    this.loadingbuttext = '正式发布'
                  }
                }
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消保存'
              })
              if (dangerState == 2) {
                this.loadingbut = false
                this.loadingbuttext = '正式发布'
              }
            })
        } else {
          this.$notify({
            title: '失败',
            message: '隐患验证失败',
            type: 'error',
            duration: 2000
          })
          if (dangerState == 2) {
            this.loadingbut = false
            this.loadingbuttext = '正式发布'
          }
          return false
        }
      })
    },
    // submitDraftForm() {
    //   this.$refs.postForm.validate((valid) => {
    //     if (valid) {
    //       const formData = new FormData()
    //       formData.append('taskId', this.taskId)
    //       formData.append('companyId', this.postForm.companyId)
    //       formData.append('dangerLevel', this.postForm.dangerLevel)
    //       formData.append('dangerName', this.postForm.dangerName)
    //       formData.append('discoverPerson', this.postForm.discoverPerson)
    //       formData.append('discoverDate', this.postForm.discoverDate)
    //       formData.append('dangerContent', this.postForm.dangerContent)
    //       formData.append('dangerRecitfyType', this.postForm.dangerRecitfyType)
    //       if (this.postForm.dangerRecitfyType == 2) {
    //         formData.append('recitfyOverdate', this.postForm.recitfyOverdate)
    //       } else {
    //         formData.append('recitfyOverdate', moment().format('YYYY/MM/DD'))
    //       }
    //       formData.append(
    //         'recitfyRequirement',
    //         this.postForm.recitfyRequirement
    //       )
    //       formData.append('dangerState', 1)
    //       this.postForm.fileList.forEach((file) => {
    //         formData.append('files', file, file.name)
    //       })
    //       // formData.append('file', this.postForm.file)
    //       addTrouble({ formData }).then((res) => {
    //         if (res.code == 20000) {
    //           this.$notify({
    //             title: '成功',
    //             message: '保存隐患草稿成功',
    //             type: 'success',
    //             duration: 2000
    //           })
    //           this.resetForm(
    //             this.postForm.companyId,
    //             this.postForm.dangerLevel,
    //             this.postForm.discoverPerson,
    //             this.postForm.discoverDate
    //           )
    //         } else {
    //           this.$notify({
    //             title: '失败',
    //             message: '保存隐患草稿失败',
    //             type: 'error',
    //             duration: 2000
    //           })
    //         }
    //       })
    //     } else {
    //       this.$notify({
    //         title: '失败',
    //         message: '隐患验证失败',
    //         type: 'error',
    //         duration: 2000
    //       })
    //       return false
    //     }
    //   })
    // },
    getEnterpriseList() {
      fetchEnterpriseListByUser().then((response) => {
        // console.log(response.data)
        this.enterpriseList = response.data
      })
    },
    // 上传之前的格式设置
    beforeAvatarUpload(file) {
      //图片上传前图片大小和类型判断
      const isImg = file.type === 'image/jpeg' || 'image/jpg' || 'image/png'
      // const isSize = file.size / 1024 / 1024 / 5 < 1
      if (!isImg) {
        this.$message.error('上传文件只能是图片格式！')
      }
      // if (!isSize) {
      //   this.$message.error('上传图片不能超过5MB！')
      // }
      // return isImg && isSize
      return isImg
    },
    httpRequest(data) {
      // console.log('httprequest')
      // console.log('data.file', data.file)
      this.postForm.fileList.push(data.file)
      // console.log('this.postForm.fileList', this.postForm.fileList)
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList, this.postForm.fileList)
      this.postForm.fileList.forEach((f, i) => {
        if (f.uid == file.uid) {
          this.postForm.fileList.splice(i, 1)
        }
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    getTroubleGradesList() {
      getBaseDicInfo({ typeId: 2 }).then((response) => {
        this.troubleGrades = response.data
      })
    },
    getRectifyTypeList() {
      getBaseDicInfo({ typeId: 1 }).then((response) => {
        this.troubleRectifyTypes = response.data
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container /deep/ .el-date-editor {
  width: 165px;
}

.fieldInfo {
  border-color: #eee;
  border-width: 1px;
  border-style: solid;
  margin-bottom: 20px;
  legend {
    color: #666;
  }
}
</style>
